////////////////////////////////////////////////////////////////////////////////
//  COPYRIGHT (C) 2010 TELECOM DIGITAL MEDIA ("TDMEDIA").
//  ALL RIGHTS RESERVED.
//
//  THIS IS CONFIDENTIAL AND PROPRIETARY INTELLECTUAL PROPERTY OWNED BY AND
//  CREATED ON BEHALF OF TDMEDIA. ANY FORM OF DISTRIBUTION, COPY,
//  MODIFICATION WITHOUT THE WRITTEN CONSENT FROM TDMEDIA IS STRICTLY
//  PROHIBITED.
////////////////////////////////////////////////////////////////////////////////
package cc.telecomdigital.tdstock.activity;

import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Process;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import cc.telecomdigital.tdstock.CommonDefn;
import cc.telecomdigital.tdstock.CustomizeDialog;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax;
import cc.telecomdigital.tdstock.CustomizeDialogDualMax.IOnDialogButtonClick;
import cc.telecomdigital.tdstock.ExceptionHandler;
import cc.telecomdigital.tdstock.ITDLApplication;
import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.SystemInfo;
import cc.telecomdigital.tdstock.Framework.Activity_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Http.H_CODE;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Services.LS_Authentication.LS_Authentication_Result;
import cc.telecomdigital.tdstock.Services.LS_UserClient.ILS_UserClient_Authentication_Report;
import cc.telecomdigital.tdstock.Services.LS_UserClient.LS_UserClient_Authentication_Result;
import cc.telecomdigital.tdstock.activity.groups.IndexGroup;
import cc.telecomdigital.tdstock.activity.groups.MonitorGroup;
import cc.telecomdigital.tdstock.activity.groups.MoreGroup;
import cc.telecomdigital.tdstock.activity.groups.StockGroup;
import cc.telecomdigital.tdstock.activity.groups.index.BMPIndexActivity;
import cc.telecomdigital.tdstock.activity.groups.index.IndexActivity;
import cc.telecomdigital.tdstock.activity.groups.monitor.PortfolioActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.BMPCurrentStockInfoActivity;
import cc.telecomdigital.tdstock.activity.groups.stock.CurrentStockInfoActivity;

/**
 * login screen entry
 * 
 * @author haibo
 * @desc modify by ouyangzhihui
 */
public class AccountLoginActivity extends Activity_Framework implements OnClickListener
{
	private static String			TAG							= AccountLoginActivity.class.getSimpleName();

	protected static final String	ACTION_INSTALL_SHORTCUT		= "com.android.launcher.action.INSTALL_SHORTCUT";
	protected static final String	EXTRA_SHORTCUT_DUPLICATE	= "duplicate";

	protected static String			_menu_exit_app_res			= null;
	protected static String			_menu_gen_launcher_res		= null;

	public static final int			EXIT_APP					= Menu.FIRST;
	public static final int			CREATE_LAUNCHER				= Menu.FIRST + 1;
//	private static String			SUCCESS_CODE				= "0";

	private Button					_login;
	private Button					_returnPre;
	private EditText				_userid;
	private EditText				_password;

//	private LogonAsyncTask2			_logonProcess;

	public static boolean			_isAnotherLogonClientAppear	= false;

	private Handler					_handler					= new Handler();
	private SharedPreferences		_prefse						= null;
	
	static public String 			errorMessage				= null;
	static public String 			iUserName;
	static public String			iPassword;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		ExceptionHandler.register(this);
		setContentView(R.layout.account_login);

		_prefse = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		_menu_exit_app_res = getResources().getString(R.string.app_exit);
		_menu_gen_launcher_res = getResources().getString(R.string.app_launcher);

		((ScrollView) findViewById(R.id.scrollview)).setScrollbarFadingEnabled(true);

		_userid = (EditText) findViewById(R.id.userid);
		_password = (EditText) findViewById(R.id.password);
		
		_login = (Button)findViewById(R.id.login_button);
		_returnPre = (Button)findViewById(R.id.btn_returnpre);
		_login.setOnClickListener(this);
		_returnPre.setOnClickListener(this);

		_password.setOnKeyListener(new OnKeyListener()
		{
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event)
			{
				if (event.isTracking() && !event.isCanceled())
				{
					return false; // this code copied from Activity.class
				}
				if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_TAB)
				{
					try
					{
						InputMethodManager mgr;
						View viewObj;

						viewObj = getCurrentFocus();
						if (viewObj != null)
						{
							mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
							if (mgr != null)
							{
								if (mgr.isActive())
									mgr.hideSoftInputFromWindow(viewObj.getWindowToken(), 0);
							}
						}
						_login.performClick();
						Thread.yield();
					}
					catch (Exception e)
					{
						e.printStackTrace();
					}
				}
				return false;
			}
		});
	}

	@Override
	public void onClick(View v)
	{
		if (!SystemInfo.isNetworkingConnected(this))
		{
			// 网络未连接...
			new CustomizeDialog(this, getResources().getString(R.string.info), "登錄錯誤，請檢查網絡連接", getResources().getString(R.string.ok)).show();
			return;
		}

		//final String prefDeviceId = _prefse.getString(CommonDefn.PREFERENCE_DEVICE_ID, "");
		//TDStockLog.i(TAG, "prefDeviceId = " + prefDeviceId);
		
		if (v == _returnPre)
		{
			if (!RealtimeStockActivity.IsCustomerForwardToAccountLogin/* || !appHost.LSClient_IsConnected()*/)
			{
				Runnable	runnable	= new Runnable()
				{
					@Override
					public void run()
					{
						TDLDemoLogonToDelayModeApp();
					}
				};
				_handler.post(runnable);
				return;
			}
			forwardToMainActivity("ReturnBack");
			return;
		}
		if (v == _login)
		{
			String userNameContent, passwordContent;
			userNameContent = _userid.getEditableText().toString();
			passwordContent = _password.getEditableText().toString();

			if ((userNameContent == null) || (passwordContent == null) || (userNameContent.length() == 0) || (passwordContent.length() == 0))
			{
				CustomizeDialog promptBox;
				promptBox = new CustomizeDialog(this, getResources().getString(R.string.info), "請填寫所需的資料.")
				{
					@Override
					public void onClick(View v)
					{
						dismiss();
					}
				};
				promptBox.setCancelable(true);
				promptBox.show();
				return;
			}

			AccountLogonToApp(_userid.getText().toString(), _password.getText().toString());
		}
	}
	
	private void forwardToMainActivity(String... params)
	{
		// Change ModeType Update UI.
		if (params.length <= 0)
		{
			// BMP Mode by ouyangzhihui 2011-10-13
			if (((ITDLApplication) getApplicationContext()).getIsBMPMode())  //data mode   --- -to  ---> BMP
			{
				BMPCurrentStockInfoActivity.isChangeModeType = true;
				BMPIndexActivity.isChangeModeType = true;

				if (StockGroup.group != null)
				{
					// StockGroup.group.GetActivityGroupHostControl().ActivityClearList();
					StockGroup.GetActivityGroupHostControl().ResetController();
					StockGroup.group.finish();
				}
				if (MonitorGroup.group != null)
				{
					// MonitorGroup.group.GetActivityGroupHostControl().ActivityClearList();
					MonitorGroup.GetActivityGroupHostControl().ResetController();
					MonitorGroup.group.finish();
				}
				if (IndexGroup.group != null)
				{
					// IndexGroup.group.GetActivityGroupHostControl().ActivityClearList();
					IndexGroup.GetActivityGroupHostControl().ResetController();
					//StockGroup.group.finish();
					IndexGroup.group.finish();   //modified by haibo in 2012-03-19
				}
				
				if(MoreGroup.group != null) 
				{
					MoreGroup.GetActivityGroupHostControl().ResetController();
					MoreGroup.group.finish();   //added by haibo in 2012-03-19
				}
				
			}
			else
			{
				//data mode   --- -to  ---> Realtime
				CurrentStockInfoActivity.isChangeModeType = true;
				PortfolioActivity.isChangeModeType = true;
				IndexActivity.isChangeModeType = true;
				
				if(MoreGroup.group != null) 
				{
					MoreGroup.GetActivityGroupHostControl().ResetController();
					MoreGroup.group.finish();   //added by haibo in 2012-03-19
				}
			}
			RealtimeStockActivity.Is_Change_Mode = true;
		}

		Intent i = new Intent(this, RealtimeStockActivity.class);
		i.setFlags(Intent.FLAG_ACTIVITY_NO_USER_ACTION | Intent.FLAG_ACTIVITY_CLEAR_TOP);
		SwitchFreeActivity(RealtimeStockActivity.class, i);
	}

	protected synchronized void handleExitApplication()
	{
		new AlertDialog.Builder(this).setTitle(
				getResources().getString(R.string.info)).setMessage(
				getResources().getString(R.string.application_exit_tips))
				.setIcon(
						getResources().getDrawable(
								R.drawable.help_menu_icon))
				.setPositiveButton(getResources().getString(R.string.ok),
						new DialogInterface.OnClickListener()
						{
							public void onClick(
									DialogInterface dialoginterface,
									int i)
							{
								((ITDLApplication) getApplicationContext())
										.setExitApp(true);
								exitApp();
							}
						}).setNegativeButton(
						getResources().getString(R.string.cancel),
						new DialogInterface.OnClickListener()
						{
							public void onClick(DialogInterface dialog,
									int whichButton)
							{
							}
						}).show();
	}

	public void exitApp()
	{
		finish();
		/* Process.killProcess(Process.myPid()); */
		Process.sendSignal(Process.myPid(), Process.SIGNAL_QUIT);
	}

	protected synchronized void genLauncher()
	{
		Intent shortcutIntent = new Intent(ACTION_INSTALL_SHORTCUT);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));
		shortcutIntent.putExtra(EXTRA_SHORTCUT_DUPLICATE, false);
		Intent intent2 = new Intent(Intent.ACTION_MAIN);
		intent2.addCategory(Intent.CATEGORY_LAUNCHER);

		intent2.setComponent(new ComponentName(this.getPackageName(), ".activity.SplashActivity"));

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent2);
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.icon));
		sendBroadcast(shortcutIntent);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		super.onCreateOptionsMenu(menu);
		menu.add(0, CREATE_LAUNCHER, 0, _menu_gen_launcher_res);
		MenuItem mItem = menu.findItem(CREATE_LAUNCHER);
		mItem.setIcon(R.drawable.back_down);
		menu.add(0, EXIT_APP, 1, _menu_exit_app_res);
		mItem = menu.findItem(EXIT_APP);
		mItem.setIcon(R.drawable.down_24_1);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch (item.getItemId())
		{
			case EXIT_APP:
				((ITDLApplication) getApplicationContext())
						.setExitApp(true);
				exitApp();
				break;
			case CREATE_LAUNCHER:
				genLauncher();
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	private void ShowMessageDialog(final String iErrorMessage)
	{
		final Runnable runnable = new Runnable()
		{
			@Override
			public void run()
			{
				if(iErrorMessage != null)
				{
					if(iUserName!=null && iPassword!=null)
					{
						_userid.setText(iUserName);
						_password.setText(iPassword);
						iUserName = null;
						iPassword = null;
					}
					
					CustomizeDialog dialogMsg;
					dialogMsg = new CustomizeDialog(actContext, getResources().getString(R.string.info), "".equals(iErrorMessage) ? getResources().getString(R.string.login_failure) : iErrorMessage);
					dialogMsg.setCancelable(true);
					dialogMsg.show();
					errorMessage = null;
				}
			}
		};
		_handler.postDelayed(runnable, 100);
	}

	@Override
	public void onResume()
	{
		super.onResume();

//		if (_logonProcess != null)
//		{
//			_logonProcess.cancel(true);
//		}
		
		CustomizeDialog.dismissAll();

		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
		else
		{
			if (!_isAnotherLogonClientAppear)
			{
				if (!SystemInfo.isNetworkingConnected(this))
				{
					// 网络未连接...
					new CustomizeDialog(this, getResources().getString(R.string.info), "登錄錯誤，請檢查網絡連接", getResources().getString(R.string.ok)).show();
					return;
				}
				else
				{
					ShowMessageDialog(errorMessage);
					// automaticallyLoginTheApp();
				}
			}
			else
			{
				fillTheFormWithCustomerInfo();

				new CustomizeDialog(this, getResources().getString(R.string.info),
						"你已在其他裝置登錄\n如有任何疑問，請致電客戶服務熱線:\n 7778-7779")
				{
					@Override
					public void onClick(View v)
					{
						/** When OK Button is clicked, dismiss the dialog */
						if (v == okButton)
						{
							dismiss();
							_isAnotherLogonClientAppear = false;
						}
					}
				}.show();
				// clear the old state
			}
		}
	}

	@Override
	protected void onRestart()
	{
		super.onRestart();

		if (((ITDLApplication) getApplicationContext()).isExitApp())
		{
			exitApp();
		}
	}

	private void fillTheFormWithCustomerInfo()
	{
		if (_prefse == null)
		{
			_prefse = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
		}
		if (_prefse != null)
		{
			boolean isAutoLogin = _prefse.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, false);
			if (isAutoLogin)
			{
				String user = _prefse.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, CommonDefn.SYSTEM_TRIAL_ACCOUNT_USER);
				String pwd = _prefse.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD, CommonDefn.SYSTEM_TRIAL_ACCOUNT_PWD);
				_userid.setText(user);
				_password.setText(pwd);
			}
		}
	}

//	public static boolean	delayTdldemoLogin	= false;

//	private void automaticallyLoginTheApp()
//	{
//		if (_prefse == null)
//		{
//			_prefse = getSharedPreferences(CommonDefn.SYSTEM_CURRENT_SETTING, Context.MODE_PRIVATE);
//		}
//		if (_prefse != null)
//		{
//			boolean isAutoLogin = _prefse.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, false);
//			boolean haveNetwork = SystemInfo.isNetworkingConnected(this);
//			if (isAutoLogin && haveNetwork)
//			{
//				String user = _prefse.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, CommonDefn.SYSTEM_TRIAL_ACCOUNT_USER);
//				String pwd = _prefse.getString(CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD, CommonDefn.SYSTEM_TRIAL_ACCOUNT_PWD);
//				_userid.setText(user);
//				_password.setText(pwd);
//
////				_isAutoLogin = true;
//				if (((ITDLApplication) getApplicationContext())
//						.getInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER) == ITDLApplication.DEFAULT_INT_VALUE)
//				{
//					_login.performClick();
//				}
//			}
//			else if (delayTdldemoLogin && haveNetwork)
//			{
////				_isAutoLogin = true;
//				if (((ITDLApplication) getApplicationContext())
//						.getInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER) == ITDLApplication.DEFAULT_INT_VALUE)
//				{
//					_login.performClick();
//				}
//			}
//			else
//			{
//				if (!haveNetwork)
//				{
//					new CustomizeDialog(this, getResources().getString(R.string.info), "登錄錯誤，請檢查網絡連接", getResources().getString(R.string.ok)).show();
//					return;
//				}
//			}
//		}
//	}

	@Override
	public void onBackPressed()
	{
		if(RealtimeStockActivity.IsCustomerForwardToAccountLogin)
		{
			super.onBackPressed();
		}
		// do nothing
	}

//	private class LogonAsyncTask2 extends AsyncTask<String, Void, Void>
//	{
//		Authentication	auth;
//		String			user;
//		String			pwd;
//		String[]		deviceId_auth;
//		String[]		auth_info;
//		ProgressDialog	_dialog;
//
//		@Override
//		protected Void doInBackground(String... params)
//		{
//			CustomerInfo.setDataMode(CommonDefn.DataMode.Realtime);
//			user = params[0];
//			pwd = params[1];
//
//			deviceId_auth = SystemInfo.GetDeviceIdAuthWifiMac(AccountLoginActivity.this);
//
//			if (SystemInfo.SUCCESS_CODE.equals(deviceId_auth[0])) // success
//			{
//				TDStockLog.d(TAG, "test code = LogonAsyncTask2");
//				// Zor 2011-12-14
//				// String edevinfo =
//				// SystemInfo.getDeviceExtraInfo(AccountLoginActivity.this);
//				auth = new Authentication(user, pwd, deviceId_auth[1],
//						new String[] {/*
//									 * edevinfo,_prefse.getString(CommonDefn.
//									 * PREFERENCE_DEVICE_ID, ""),
//									 * SystemInfo.getAppVersionName
//									 * (AccountLoginActivity.this)
//									 */});
//				auth_info = auth.getAuthentication();
//			}
//			return null;
//		}
//
//		@Override
//		protected void onCancelled()
//		{
//			super.onCancelled();
//			if (_dialog != null)
//				_dialog.dismiss();
//		}
//
//		@Override
//		protected void onPreExecute()
//		{
//			super.onPreExecute();
//			_dialog = new ProgressDialog(AccountLoginActivity.this, Html.fromHtml("正在初始化數據並連接至伺服器<br/>請稍候...").toString());
//			_dialog.show();
//		}
//
//		@Override
//		protected void onPostExecute(Void result)
//		{
//			super.onPostExecute(result);
//			if (_dialog != null)
//				_dialog.dismiss();
//			if (SystemInfo.SUCCESS_CODE.equals(deviceId_auth[0])) // success
//			{
//				Logon(auth_info, user, pwd);
//			}
//			else
//			// failed
//			{
//				if (deviceId_auth[2].length() < 2)
//					deviceId_auth[2] = "操作失敗，請稍後再试。";
//
//				new CustomizeDialog(AccountLoginActivity.this, getResources().getString(R.string.info),
//						deviceId_auth[2], getResources().getString(R.string.ok))
//				{
//					@Override
//					public void onClick(View v)
//					{
//						if (v == okButton)
//						{
//							// SystemInfo.initLoginApp(getApplicationContext(),
//							// CommonDefn.ModeType.DELARY, null, null, null,
//							// null);
//							// forwardToMainActivity();
//							dismissAll();
//							((ITDLApplication) getApplicationContext()).setExitApp(true);
//							exitApp();
//						}
//					}
//				}.show();
//			}
//		}
//	}
//	
//	private void autoLoginExcuteCode(String user, String pwd, String deviceId)
//	{
//		Authentication auth = new Authentication(user, pwd, deviceId, new String[] {});
//		String[] auth_info = auth.getAuthentication();
//
//		Logon(auth_info, user, pwd);
//	}
//
//	private void Logon(String[] auth_info, String user, String pwd)
//	{
//		if (auth_info[3].equals(SUCCESS_CODE))
//		{
//			_isAnotherLogonClientAppear = false;
//			TDStockLog.d(TAG, "auth_info=" + auth_info[0] + " , " + auth_info[1]);
//
//			CommonDefn.ModeType modeType = CommonDefn.ModeType.ACCOUNTLOGIN;
//
//			if (CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY.equals(user))
//			{
//				modeType = CommonDefn.ModeType.DELARY;
//			}
//			else
//			{
//				if (_prefse != null)
//				{
//					boolean isAutoLogin = _prefse.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, true);
//					_prefse.edit().putBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, isAutoLogin)
//							.putString(CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, user)
//							.putString(CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD, pwd)
//							.commit();
//				}
//			}
//			SystemInfo.initLoginApp(getApplicationContext(), modeType, user, pwd, auth_info[0], auth_info[1]);
//
//			softWindowHide()();
//
//			((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER, ITDLApplication.DEFAULT_INT_VALUE);
//			((ITDLApplication) getApplicationContext()).setReadyToChangeMode(true);
//
//			String svcPlan = auth_info[4]; // svcPlan i.e. 1111111110Z110000001
//			TDStockLog.d(TAG, "svcPlan=" + svcPlan);
//			((ITDLApplication) getApplicationContext()).SetServicePlan(svcPlan);
//
//			forwardToMainActivity();
//		}
//		else
//		{
//			((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER,  ITDLApplication.DEFAULT_INT_VALUE);
//
//			String errorInfo = getResources().getString(R.string.login_failure); // default
//			// failure
//			// message;
//			if (auth_info[2].trim().length() > 0)
//			{
//				errorInfo = auth_info[2].trim(); // server response message;
//			}
//
//			new CustomizeDialog(AccountLoginActivity.this, getResources().getString(R.string.info), errorInfo,
//					getResources().getString(R.string.ok)).show();
//
//		}
//	}
	
	private void softWindowHide()
	{
		try
		{
			Object service = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			InputMethodManager imm = (InputMethodManager) service;
			if (_password.isFocused())
			{
				imm.hideSoftInputFromWindow(_password.getWindowToken(), 0); 
			}
			if (_userid.isFocused())
			{
				imm.hideSoftInputFromWindow(_userid.getWindowToken(), 0);
			}
			Thread.yield();
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
	
	private void TDLDemoLogonToDelayModeApp()
	{
		AutoLoginToApp(CommonDefn.ACCOUNT_USER_NAME_TRIAL_DELAY, CommonDefn.ACCOUNT_USER_PWD_TRIAL_DELAY, null, CommonDefn.ModeType.DELARY);
	}
	private void AccountLogonToApp(String iUserName, String iPassword)
	{
		AutoLoginToApp(iUserName, iPassword, null, CommonDefn.ModeType.ACCOUNTLOGIN);
	}

	private void AutoLoginToApp(final String userName, final String password, final String activateCode, final CommonDefn.ModeType iModeType)
	{
		TDStockLog.d(TAG, "LoginMode=>" + iModeType);
		H_CODE statusCode;
		ILS_UserClient_Authentication_Report report = new ILS_UserClient_Authentication_Report()
		{
			@Override
			public void LS_UserClient_Authentication_Response(LS_UserClient_Authentication_Result iResponse)
			{
				TDStockLog.d(TAG, "LogonToApp=>callback: statusCode=" + iResponse.statusCode + ", errMsg="+iResponse.errorMessage);
				//if ((iResponse == null) || (iResponse.successfulSend == false))
				if ((iResponse == null) || (iResponse.successfulSend == false) || (iResponse.statusCode == null))				
				{
					/*if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
					{
						AccountLoginActivity.iUserName = userName;
						AccountLoginActivity.iPassword = password;
					}*/
//					Toast.makeText(actContext, "登錄失敗!", Toast.LENGTH_SHORT).show();
					ShowMessageDialog(getString(R.string.login_failure));					
//					ShowMessageDialog(iResponse==null?getResources().getString(R.string.login_failure):iResponse.errorMessage);
					return;
				}

//				if ((iResponse.statusCode == null) || !iResponse.statusCode.equals("0"))
//				{
//					/*if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
//					{
//						AccountLoginActivity.iUserName = userName;
//						AccountLoginActivity.iPassword = password;
//					}*/
////					Toast.makeText(actContext, "登錄失敗:" + " statusCode=" + iResponse.statusCode + ", errMsg=" + iResponse.errorMessage, Toast.LENGTH_SHORT).show();
//					
//					ShowMessageDialog(iResponse.errorMessage);
//					return;
//				}

				if (iResponse.statusCode.equals("0"))
				{
//					if(CommonDefn.ModeType.ACCOUNTLOGIN != iModeType)
					if(!iResponse.errorMessage.trim().equals(""))
						BaseActivity.loginResult = new LS_Authentication_Result(iResponse);


					if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
					{
						if (_prefse != null)
						{
							boolean isAutoLogin = _prefse.getBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, true);
							_prefse.edit()
								.putBoolean(CommonDefn.PREFERENCE_IS_AUTO_LOGIN_APP, isAutoLogin)
								.putString(CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, userName)
								.putString(CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD, password)
								.commit();
						}
						
						softWindowHide();
						
						((ITDLApplication) getApplicationContext()).putInt(CommonDefn.PREFERENCE_AUTO_LOGIN_FAIL_COUNTER, ITDLApplication.DEFAULT_INT_VALUE);
						((ITDLApplication) getApplicationContext()).setReadyToChangeMode(true);
					}
					
					SystemInfo.initLoginApp(getApplicationContext(), iModeType, userName, password, null, null);
					((ITDLApplication) getApplicationContext()).SetServicePlan(appHost.GetLSClient_ServicePlan());
					forwardToMainActivity();
					return;
				}
				
				final String            extraContent;
				CustomizeDialogDualMax  msgDialog;
				
				msgDialog = new CustomizeDialogDualMax(actContext);
				msgDialog.SetOnCancelFeature(false, null);
				
				msgDialog.SetHeader("提示");
				msgDialog.SetMsgContent(iResponse.errorMessage);
				
				//Create a downloadable message if needed
				extraContent = iResponse.linkContent;
				if ((extraContent != null) && (extraContent.length() != 0 ))
				{
					msgDialog.SetDualButton( iResponse.linkCaption, 
										 new IOnDialogButtonClick()
										{
											@Override
											public void OnResponse()
											{
												Uri    uriObj;
												Intent intentObj;
												String linkContent;
								
												if(iUserName!=null && iPassword!=null)
												{
													_userid.setText(iUserName);
													_password.setText(iPassword);
													iUserName = null;
													iPassword = null;
												}												
												
												linkContent = extraContent;					
												if ((linkContent == null) || (linkContent.length() == 0))
													return;
												
												intentObj = new Intent(Intent.ACTION_VIEW);
												uriObj = Uri.parse(linkContent);
												intentObj.setData(uriObj);
												startActivity(intentObj);
											}				
										}, getString(R.string.ok),
										new IOnDialogButtonClick()
										{
											@Override
											public void OnResponse()
											{								
												if(iUserName!=null && iPassword!=null)
												{
													_userid.setText(iUserName);
													_password.setText(iPassword);
													iUserName = null;
													iPassword = null;
												}												
											}											
										});
				}					
				else
				{
					msgDialog.SetSingleButton(getString(R.string.ok), 
										new IOnDialogButtonClick()
										{
											@Override
											public void OnResponse()
											{								
												if(iUserName!=null && iPassword!=null)
												{
													_userid.setText(iUserName);
													_password.setText(iPassword);
													iUserName = null;
													iPassword = null;
												}												
											}											
										});	
				}
				msgDialog.show();
			}
		};
		
		if(CommonDefn.ModeType.ACTIVECODE == iModeType)
		{
			statusCode = HttpAppInfo.SendFrameworkTrialAuthRequest(activateCode, report);
		}
		else
		{
			statusCode = HttpAppInfo.SendFrameworkILoginAuthRequest(userName, password, report);
		}
		
		TDStockLog.d(TAG, "LogonToApp=>status:" + statusCode);
		if(statusCode != H_CODE.OK)
		{
			/*if(CommonDefn.ModeType.ACCOUNTLOGIN == iModeType)
			{
				AccountLoginActivity.iUserName = userName;
				AccountLoginActivity.iPassword = password;
			}*/
			ShowMessageDialog(getResources().getString(R.string.login_failure));
		}
	}
}
